<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1">
<title>Using StAX - The Java EE 5 Tutorial</title>
<meta name="robots" content="index,follow">
<meta name="robots" content="index,follow">
<meta name="date" content="2008-10-01">
<link rel="stylesheet" type="text/css" href="css/default.css">
<link rel="stylesheet" type="text/css" href="css/ipg.css">
<link rel="stylesheet" type="text/css" href="css/j5eetutorial.css">
</head>

<body>

<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tbody>
   <tr valign="top">
      <td><p class="toc level1"><a href="docinfo.html">Document Information</a></p>
<p class="toc level1 tocsp"><a href="gexaf.html">Preface</a></p>
<p class="toc level1 tocsp"><a href="gfirp.html">Part&nbsp;I&nbsp;Introduction</a></p>
<p class="toc level2"><a href="bnaaw.html">1.&nbsp;&nbsp;Overview</a></p>
<p class="toc level2"><a href="gfiud.html">2.&nbsp;&nbsp;Using the Tutorial Examples</a></p>
<p class="toc level1 tocsp"><a href="bnadp.html">Part&nbsp;II&nbsp;The Web Tier</a></p>
<p class="toc level2"><a href="bnadr.html">3.&nbsp;&nbsp;Getting Started with Web Applications</a></p>
<p class="toc level2"><a href="bnafd.html">4.&nbsp;&nbsp;Java Servlet Technology</a></p>
<p class="toc level2"><a href="bnagx.html">5.&nbsp;&nbsp;JavaServer Pages Technology</a></p>
<p class="toc level2"><a href="bnajo.html">6.&nbsp;&nbsp;JavaServer Pages Documents</a></p>
<p class="toc level2"><a href="bnakc.html">7.&nbsp;&nbsp;JavaServer Pages Standard Tag Library</a></p>
<p class="toc level2"><a href="bnalj.html">8.&nbsp;&nbsp;Custom Tags in JSP Pages</a></p>
<p class="toc level2"><a href="bnaon.html">9.&nbsp;&nbsp;Scripting in JSP Pages</a></p>
<p class="toc level2"><a href="bnaph.html">10.&nbsp;&nbsp;JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnaqz.html">11.&nbsp;&nbsp;Using JavaServer Faces Technology in JSP Pages</a></p>
<p class="toc level2"><a href="bnatx.html">12.&nbsp;&nbsp;Developing with JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnavg.html">13.&nbsp;&nbsp;Creating Custom UI Components</a></p>
<p class="toc level2"><a href="bnawo.html">14.&nbsp;&nbsp;Configuring JavaServer Faces Applications</a></p>
<p class="toc level2"><a href="bnaxu.html">15.&nbsp;&nbsp;Internationalizing and Localizing Web Applications</a></p>
<p class="toc level1 tocsp"><a href="bnayk.html">Part&nbsp;III&nbsp;Web Services</a></p>
<p class="toc level2"><a href="bnayl.html">16.&nbsp;&nbsp;Building Web Services with JAX-WS</a></p>
<p class="toc level2"><a href="bnazf.html">17.&nbsp;&nbsp;Binding between XML Schema and Java Classes</a></p>
<p class="toc level2"><a href="bnbdv.html">18.&nbsp;&nbsp;Streaming API for XML</a></p>
<p class="toc level3"><a href="bnbdw.html">Why StAX?</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdx">Streaming versus DOM</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdy">Pull Parsing versus Push Parsing</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdz">StAX Use Cases</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbea">Comparing StAX to Other JAXP APIs</a></p>
<p class="toc level3 tocsp"><a href="bnbec.html">StAX API</a></p>
<p class="toc level4"><a href="bnbec.html#bnbed">Cursor API</a></p>
<p class="toc level4"><a href="bnbec.html#bnbee">Iterator API</a></p>
<p class="toc level5"><a href="bnbec.html#bnbef">Iterator Event Types</a></p>
<p class="toc level5"><a href="bnbec.html#bnbeh">Example of Event Mapping</a></p>
<p class="toc level4 tocsp"><a href="bnbec.html#bnbej">Choosing between Cursor and Iterator APIs</a></p>
<p class="toc level5"><a href="bnbec.html#bnbek">Development Goals</a></p>
<p class="toc level5"><a href="bnbec.html#bnbel">Comparing Cursor and Iterator APIs</a></p>
<div class="onpage">
<p class="toc level3 tocsp"><a href="">Using StAX</a></p>
<p class="toc level4"><a href="#bnben">StAX Factory Classes</a></p>
<p class="toc level5"><a href="#bnbeo"><tt>XMLInputFactory</tt> Class</a></p>
<p class="toc level5"><a href="#bnbeq"><tt>XMLOutputFactory</tt> Class</a></p>
<p class="toc level5"><a href="#bnber"><tt>XMLEventFactory</tt> Class</a></p>
<p class="toc level4 tocsp"><a href="#bnbes">Resources, Namespaces, and Errors</a></p>
<p class="toc level5"><a href="#bnbet">Resource Resolution</a></p>
<p class="toc level5"><a href="#bnbeu">Attributes and Namespaces</a></p>
<p class="toc level5"><a href="#bnbev">Error Reporting and Exception Handling</a></p>
<p class="toc level4 tocsp"><a href="#bnbew">Reading XML Streams</a></p>
<p class="toc level5"><a href="#bnbex">Using <tt>XMLStreamReader</tt></a></p>
<p class="toc level5"><a href="#bnbfb">Using <tt>XMLEventReader</tt></a></p>
<p class="toc level4 tocsp"><a href="#bnbfe">Writing XML Streams</a></p>
<p class="toc level5"><a href="#bnbff">Using <tt>XMLStreamWriter</tt></a></p>
<p class="toc level5"><a href="#bnbfg">Using <tt>XMLEventWriter</tt></a></p>
</div>
<p class="toc level3 tocsp"><a href="bnbfi.html">Sun's Streaming XML Parser Implementation</a></p>
<p class="toc level4"><a href="bnbfi.html#bnbfj">Reporting CDATA Events</a></p>
<p class="toc level4"><a href="bnbfi.html#bnbfk">Streaming XML Parser Factories Implementation</a></p>
<p class="toc level3 tocsp"><a href="bnbfl.html">Example Code</a></p>
<p class="toc level4"><a href="bnbfl.html#bnbfm">Example Code Organization</a></p>
<p class="toc level4"><a href="bnbfl.html#bnbfn">Example XML Document</a></p>
<p class="toc level4"><a href="bnbfl.html#bnbfo">Cursor Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfp">Stepping through Events</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfq">Returning String Representations</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfr">Building and Running the Cursor Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfs">Building and Running the Cursor Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="bnbfl.html#bnbft">Cursor-to-Event Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfu">Instantiating an <tt>XMLEventAllocator</tt></a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfv">Creating an Event Iterator</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfw">Creating the Allocator Method</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfx">Building and Running the Cursor-to-Event Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbfy">Building and Running the Cursor-to-Event Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="bnbfl.html#bnbfz">Event Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbga">Creating an Input Factory</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgb">Creating an Event Reader</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgc">Creating an Event Iterator</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgd">Getting the Event Stream</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbge">Returning the Output</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgf">Building and Running the Event Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgg">Building and Running the Event Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="bnbfl.html#bnbgh">Filter Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgi">Implementing the <tt>StreamFilter</tt> Class</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgj">Creating an Input Factory</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgk">Creating the Filter</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgl">Capturing the Event Stream</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgm">Filtering the Stream</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgn">Returning the Output</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgo">Building and Running the Filter Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgp">Building and Running the Filter Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="bnbfl.html#bnbgq">Read-and-Write Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgr">Creating an Event Producer/Consumer</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgs">Creating an Iterator</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgt">Creating a Writer</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgu">Returning the Output</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgv">Building and Running the Read-and-Write Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgw">Building and Running the Read-and-Write Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="bnbfl.html#bnbgx">Writer Example</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgy">Creating the Output Factory</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbgz">Creating a Stream Writer</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbha">Writing the Stream</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbhb">Returning the Output</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbhc">Building and Running the Writer Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="bnbfl.html#bnbhd">Building and Running the Writer Example Using Ant</a></p>
<p class="toc level3 tocsp"><a href="bnbhe.html">Further Information about StAX</a></p>
<p class="toc level2 tocsp"><a href="bnbhf.html">19.&nbsp;&nbsp;SOAP with Attachments API for Java</a></p>
<p class="toc level1 tocsp"><a href="bnblr.html">Part&nbsp;IV&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbls.html">20.&nbsp;&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbnb.html">21.&nbsp;&nbsp;Getting Started with Enterprise Beans</a></p>
<p class="toc level2"><a href="bnboc.html">22.&nbsp;&nbsp;Session Bean Examples</a></p>
<p class="toc level2"><a href="bnbpk.html">23.&nbsp;&nbsp;A Message-Driven Bean Example</a></p>
<p class="toc level1 tocsp"><a href="bnbpy.html">Part&nbsp;V&nbsp;Persistence</a></p>
<p class="toc level2"><a href="bnbpz.html">24.&nbsp;&nbsp;Introduction to the Java Persistence API</a></p>
<p class="toc level2"><a href="bnbrl.html">25.&nbsp;&nbsp;Persistence in the Web Tier</a></p>
<p class="toc level2"><a href="bnbrs.html">26.&nbsp;&nbsp;Persistence in the EJB Tier</a></p>
<p class="toc level2"><a href="bnbtg.html">27.&nbsp;&nbsp;The Java Persistence Query Language</a></p>
<p class="toc level1 tocsp"><a href="bnbwi.html">Part&nbsp;VI&nbsp;Services</a></p>
<p class="toc level2"><a href="bnbwj.html">28.&nbsp;&nbsp;Introduction to Security in the Java EE Platform</a></p>
<p class="toc level2"><a href="bnbyk.html">29.&nbsp;&nbsp;Securing Java EE Applications</a></p>
<p class="toc level2"><a href="bncas.html">30.&nbsp;&nbsp;Securing Web Applications</a></p>
<p class="toc level2"><a href="bncdq.html">31.&nbsp;&nbsp;The Java Message Service API</a></p>
<p class="toc level2"><a href="bncgv.html">32.&nbsp;&nbsp;Java EE Examples Using the JMS API</a></p>
<p class="toc level2"><a href="bncih.html">33.&nbsp;&nbsp;Transactions</a></p>
<p class="toc level2"><a href="bncjh.html">34.&nbsp;&nbsp;Resource Connections</a></p>
<p class="toc level2"><a href="bncjx.html">35.&nbsp;&nbsp;Connector Architecture</a></p>
<p class="toc level1 tocsp"><a href="bnckn.html">Part&nbsp;VII&nbsp;Case Studies</a></p>
<p class="toc level2"><a href="bncko.html">36.&nbsp;&nbsp;The Coffee Break Application</a></p>
<p class="toc level2"><a href="bnclz.html">37.&nbsp;&nbsp;The Duke's Bank Application</a></p>
<p class="toc level1 tocsp"><a href="gexbq.html">Part&nbsp;VIII&nbsp;Appendixes</a></p>
<p class="toc level2"><a href="bncno.html">A.&nbsp;&nbsp;Java Encoding Schemes</a></p>
<p class="toc level2"><a href="bncnq.html">B.&nbsp;&nbsp;Preparation for Java EE Certification Exams</a></p>
<p class="toc level2"><a href="bncnt.html">C.&nbsp;&nbsp;About the Authors</a></p>
<p class="toc level1 tocsp"><a href="idx-1.html">Index</a></p>
</td>
      <td width="10px">&nbsp;</td>
      <td width="705px">
         <div class="header">
             <div class="header-links-top">
                 <a href="http://java.sun.com">java.sun.com</a> |
                 <a href="http://docs.sun.com/">docs.sun.com</a><br>
             </div> 
             <img src="graphics/tutorialBanner.gif" width="704" height="120" alt="The Java&trade; EE 5 Tutorial"/>
             <div class="header-links">
	         <a href="index.html">Home</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/download.html">Download</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/JavaEETutorial.pdf">PDF</a> |
                 <a href="http://java.sun.com/javaee/5/docs/api/index.html">API</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/faq.html">FAQ</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/search.html">Search</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/sendusmail.html">Feedback</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/history.html">History</a>
             </div>
             <div class="navigation">
                 <a href="bnbec.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
                 <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
                 <a href="bnbfi.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
             </div>
         </div>

	 <div class="maincontent">      	 
             

<a name="bnbem"></a><h3>Using StAX</h3>
<a name="indexterm-1846"></a><p>In general, StAX programmers create XML stream readers, writers, and events by using
the <tt>XMLInputFactory</tt>, <tt>XMLOutputFactory</tt>, and <tt>XMLEventFactory</tt> classes. Configuration is done by setting properties on
the factories, whereby implementation-specific settings can be passed to the underlying implementation using
the <tt>setProperty</tt> method on the factories. Similarly, implementation-specific settings can be queried using
the <tt>getProperty</tt> factory method.</p><p>The <tt>XMLInputFactory</tt>, <tt>XMLOutputFactory</tt>, and <tt>XMLEventFactory</tt> classes are described below, followed by discussions of resource
allocation, namespace and attribute management, error handling, and then finally reading and writing
streams using the cursor and iterator APIs.</p>

<a name="bnben"></a><h4>StAX Factory Classes</h4>
<a name="indexterm-1847"></a><a name="indexterm-1848"></a><p>The StAX factory classes. <tt>XMLInputFactory</tt>, <tt>XMLOutputFactory</tt>, and <tt>XMLEventFactory</tt>, let you define and configure
implementation instances of XML stream reader, stream writer, and event classes.</p>

<a name="bnbeo"></a><h5><tt>XMLInputFactory</tt> Class</h5>
<a name="indexterm-1849"></a><a name="indexterm-1850"></a><p>The <tt>XMLInputFactory</tt> class lets you configure implementation instances of XML stream reader processors
created by the factory. New instances of the abstract class <tt>XMLInputFactory</tt> are created by
calling the <tt>newInstance</tt> method on the class. The static method <tt>XMLInputFactory.newInstance</tt> is then
used to create a new factory instance.</p><p>Deriving from JAXP, the <tt>XMLInputFactory.newInstance</tt> method determines the specific <tt>XMLInputFactory</tt> implementation class to load
by using the following lookup procedure:</p>
<ol><li><p>Use the <tt>javax.xml.stream.XMLInputFactory</tt> system property.</p></li>
<li><p>Use the <tt>lib/xml.stream.properties</tt> file in the J2SE Java Runtime Environment (JRE) directory.</p></li>
<li><p>Use the Services API, if available, to determine the classname by looking in the <tt>META-INF/services/javax.xml.stream.XMLInputFactory</tt> files in JAR files available to the JRE.</p></li>
<li><p>Use the platform default <tt>XMLInputFactory</tt> instance.</p></li></ol>
<p>After getting a reference to an appropriate <tt>XMLInputFactory</tt>, an application can use the
factory to configure and create stream instances. <a href="#bnbep">Table&nbsp;18-4</a> lists the properties supported by
<tt>XMLInputFactory</tt>. See the StAX specification for a more detailed listing.</p><a name="bnbep"></a><h6>Table&nbsp;18-4 <tt>javax.xml.stream.XMLInputFactory</tt> Properties</h6><table><col width="35%"><col width="64%"><tr><th align="left" valign="top" scope="column"><p>Property</p></th>
<th align="left" valign="top" scope="column"><p>Description</p></th>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>isValidating</tt></p></td>
<td align="left" valign="top" scope="row"><p>Turns on implementation-specific validation.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>isCoalescing</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b>
Requires the processor to coalesce adjacent character data.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>isNamespaceAware</tt></p></td>
<td align="left" valign="top" scope="row"><p>Turns off namespace support. All implementations
must support namespaces. Support for non-namespace-aware documents is optional.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>isReplacingEntityReferences</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b> Requires the processor to
replace internal entity references with their replacement value and report them as characters or
the set of events that describe the entity.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>isSupportingExternalEntities</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b> Requires the processor to
resolve external parsed entities.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>reporter</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b> Sets and gets the implementation of the <tt>XMLReporter</tt> interface.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>resolver</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b> Sets
and gets the implementation of the <tt>XMLResolver</tt> interface.</p></td>
</tr>
<tr><td align="left" valign="top" scope="row"><p><tt>allocator</tt></p></td>
<td align="left" valign="top" scope="row"><p><b>(Required)</b> Sets and gets the implementation
of the <tt>XMLEventAllocator</tt> interface.</p></td>
</tr>
</table>

<a name="bnbeq"></a><h5><tt>XMLOutputFactory</tt> Class</h5>
<a name="indexterm-1851"></a><a name="indexterm-1852"></a><p>New instances of the abstract class <tt>XMLOutputFactory</tt> are created by calling the <tt>newInstance</tt>
method on the class. The static method <tt>XMLOutputFactory.newInstance</tt> is then used to create a
new factory instance. The algorithm used to obtain the instance is the same
as for <tt>XMLInputFactory</tt> but references the <tt>javax.xml.stream.XMLOutputFactory</tt> system property.</p><p><tt>XMLOutputFactory</tt> supports only one property, <tt>javax.xml.stream.isRepairingNamespaces</tt>. This property is required, and its purpose
is to create default prefixes and associate them with Namespace URIs. See the
StAX specification for more information.</p>

<a name="bnber"></a><h5><tt>XMLEventFactory</tt> Class</h5>
<a name="indexterm-1853"></a><a name="indexterm-1854"></a><p>New instances of the abstract class <tt>XMLEventFactory</tt> are created by calling the <tt>newInstance</tt>
method on the class. The static method <tt>XMLEventFactory.newInstance</tt> is then used to create a
new factory instance. This factory references the <tt>javax.xml.stream.XMLEventFactory</tt> property to instantiate the
factory. The algorithm used to obtain the instance is the same as for
<tt>XMLInputFactory</tt> and <tt>XMLOutputFactory</tt> but references the <tt>javax.xml.stream.XMLEventFactory</tt> system property.</p><p>There are no default properties for <tt>XMLEventFactory</tt>.</p>

<a name="bnbes"></a><h4>Resources, Namespaces, and Errors</h4>
<a name="indexterm-1855"></a><p>The StAX specification handles resource resolution, attributes and namespace, and errors and exceptions
as described below.</p>

<a name="bnbet"></a><h5>Resource Resolution</h5>
<p>The <tt>XMLResolver</tt> interface provides a means to set the method that resolves resources
during XML processing. An application sets the interface on <tt>XMLInputFactory</tt>, which then sets
the interface on all processors created by that factory instance.</p>

<a name="bnbeu"></a><h5>Attributes and Namespaces</h5>
<p>Attributes are reported by a StAX processor using lookup methods and strings in
the cursor interface, and <tt>Attribute</tt> and <tt>Namespace</tt> events in the iterator interface.
Note here that namespaces are treated as attributes, although namespaces are reported separately
from attributes in both the cursor and iterator APIs. Note also that namespace
processing is optional for StAX processors. See the StAX specification for complete information about
namespace binding and optional namespace processing.</p>

<a name="bnbev"></a><h5>Error Reporting and Exception Handling</h5>
<p>All fatal errors are reported by way of the <tt>javax.xml.stream.XMLStreamException</tt> interface. All
nonfatal errors and warnings are reported using the <tt>javax.xml.stream.XMLReporter</tt> interface.</p>

<a name="bnbew"></a><h4>Reading XML Streams</h4>
<a name="indexterm-1856"></a><a name="indexterm-1857"></a><p>As described earlier in this chapter, the way you read XML streams
with a StAX processor, and what you get back, vary significantly depending on
whether you are using the StAX cursor API or the event iterator API.
The following two sections describe how to read XML streams with each of
these APIs.</p>

<a name="bnbex"></a><h5>Using <tt>XMLStreamReader</tt></h5>
<a name="indexterm-1858"></a><a name="indexterm-1859"></a><p>The <tt>XMLStreamReader</tt> interface in the StAX cursor API lets you read XML streams
or documents in a forward direction only, one item in the infoset at
a time. The following methods are available for pulling data from the stream
or skipping unwanted events:</p>
<ul><li><p>Get the value of an attribute</p></li>
<li><p>Read XML content</p></li>
<li><p>Determine whether an element has content or is empty</p></li>
<li><p>Get indexed access to a collection of attributes</p></li>
<li><p>Get indexed access to a collection of namespaces</p></li>
<li><p>Get the name of the current event (if applicable)</p></li>
<li><p>Get the content of the current event (if applicable)</p></li></ul>
<p>Instances of <tt>XMLStreamReader</tt> have at any one time a single current event on
which its methods operate. When you create an instance of <tt>XMLStreamReader</tt> on a
stream, the initial current event is the <tt>START_DOCUMENT</tt> state. The <tt>XMLStreamReader.next</tt> method can
then be used to step to the next event in the stream.</p>

<a name="bnbey"></a><h5>Reading Properties, Attributes, and Namespaces</h5>
<p>The <tt>XMLStreamReader.next</tt> method loads the properties of the next event in the stream.
You can then access those properties by calling the <tt>XMLStreamReader.getLocalName</tt> and <tt>XMLStreamReader.getText</tt> methods.</p><p>When the <tt>XMLStreamReader</tt> cursor is over a <tt>StartElement</tt> event, it reads the
name and any attributes for the event, including the namespace. All attributes for
an event can be accessed using an index value, and can also be
looked up by namespace URI and local name. Note, however, that only the
namespaces declared on the current <tt>StartEvent</tt> are available; previously declared namespaces are not
maintained, and redeclared namespaces are not removed.</p>

<a name="bnbez"></a><h5><tt>XMLStreamReader</tt> Methods</h5>
<p><tt>XMLStreamReader</tt> provides the following methods for retrieving information about namespaces and attributes:</p><pre>int getAttributeCount();
String getAttributeNamespace(int index);
String getAttributeLocalName(int index);
String getAttributePrefix(int index);
String getAttributeType(int index);
String getAttributeValue(int index);
String getAttributeValue(String namespaceUri, String localName);
boolean isAttributeSpecified(int index);</pre><p>Namespaces can also be accessed using three additional methods:</p><pre>int getNamespaceCount();
String getNamespacePrefix(int index);
String getNamespaceURI(int index);</pre>

<a name="bnbfa"></a><h5>Instantiating an <tt>XMLStreamReader</tt></h5>
<p>This example, taken from the StAX specification, shows how to instantiate an input
factory, create a reader, and iterate over the elements of an XML stream:</p><pre>XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader r = f.createXMLStreamReader( ... );
while(r.hasNext()) {
    r.next();
}</pre>

<a name="bnbfb"></a><h5>Using <tt>XMLEventReader</tt></h5>
<a name="indexterm-1860"></a><a name="indexterm-1861"></a><p>The <tt>XMLEventReader</tt> API in the StAX event iterator API provides the means to
map events in an XML stream to allocated event objects that can be
freely reused, and the API itself can be extended to handle custom events.</p><p><tt>XMLEventReader</tt> provides four methods for iteratively parsing XML streams:</p>
<ul><li><p><tt>next</tt>: Returns the next event in the stream</p></li>
<li><p><tt>nextEvent</tt>: Returns the next typed XMLEvent</p></li>
<li><p><tt>hasNext</tt>: Returns true if there are more events to process in the stream</p></li>
<li><p><tt>peek</tt>: Returns the event but does not iterate to the next event</p></li></ul>
<p>For example, the following code snippet illustrates the <tt>XMLEventReader</tt> method declarations:</p><pre>package javax.xml.stream;
import java.util.Iterator;
public interface XMLEventReader extends Iterator {
    public Object next();
    public XMLEvent nextEvent() throws XMLStreamException;
    public boolean hasNext();
    public XMLEvent peek() throws XMLStreamException;
    ...
}</pre><p>To read all events on a stream and then print them, you
could use the following:</p><pre>while(stream.hasNext()) {
    XMLEvent event = stream.nextEvent();
    System.out.print(event);
}</pre>

<a name="bnbfc"></a><h5>Reading Attributes</h5>
<p>You can access attributes from their associated <tt>javax.xml.stream.StartElement</tt>, as follows:</p><pre>public interface StartElement extends XMLEvent {
    public Attribute getAttributeByName(QName name);
    public Iterator getAttributes();
}</pre><p>You can use the <tt>getAttributes</tt> method on the <tt>StartElement</tt> interface to use
an <tt>Iterator</tt> over all the attributes declared on that <tt>StartElement</tt>.</p>

<a name="bnbfd"></a><h5>Reading Namespaces</h5>
<p>Similar to reading attributes, namespaces are read using an <tt>Iterator</tt> created by
calling the <tt>getNamespaces</tt> method on the <tt>StartElement</tt> interface. Only the namespace for the current
<tt>StartElement</tt> is returned, and an application can get the current namespace context by
using <tt>StartElement.getNamespaceContext</tt>.</p>

<a name="bnbfe"></a><h4>Writing XML Streams</h4>
<a name="indexterm-1862"></a><a name="indexterm-1863"></a><p>StAX is a bidirectional API, and both the cursor and event iterator APIs
have their own set of interfaces for writing XML streams. As with
the interfaces for reading streams, there are significant differences between the writer APIs for
cursor and event iterator. The following sections describe how to write XML streams
using each of these APIs.</p>

<a name="bnbff"></a><h5>Using <tt>XMLStreamWriter</tt></h5>
<a name="indexterm-1864"></a><a name="indexterm-1865"></a><p>The <tt>XMLStreamWriter</tt> interface in the StAX cursor API lets applications write back to
an XML stream or create entirely new streams. XMLStreamWriter has methods that let
you:</p>
<ul><li><p>Write well-formed XML</p></li>
<li><p>Flush or close the output</p></li>
<li><p>Write qualified names</p></li></ul>
<p>Note that <tt>XMLStreamWriter</tt> implementations are not required to perform well-formedness or validity checks
on input. While some implementations may perform strict error checking, others may not.
The rules you implement are applied to properties defined in the <tt>XMLOutputFactory</tt> class.</p><p>The <tt>writeCharacters</tt> method is used to escape characters such as <tt>&amp;</tt>, <tt>&lt;</tt>, <tt>></tt>, and
<tt>"</tt>. Binding prefixes can be handled by either passing the actual value for
the prefix, by using the <tt>setPrefix</tt> method, or by setting the property for
defaulting namespace declarations.</p><p>The following example, taken from the StAX specification, shows how to instantiate an
output factory, create a writer, and write XML output:</p><pre>XMLOutputFactory output = XMLOutputFactory.newInstance();
XMLStreamWriter writer = output.createXMLStreamWriter( ... );
writer.writeStartDocument();
writer.setPrefix("c","http://c");
writer.setDefaultNamespace("http://c");
writer.writeStartElement("http://c","a");
writer.writeAttribute("b","blah");
writer.writeNamespace("c","http://c");
writer.writeDefaultNamespace("http://c");
writer.setPrefix("d","http://c");
writer.writeEmptyElement("http://c","d");
writer.writeAttribute("http://c","chris","fry");
writer.writeNamespace("d","http://c");
writer.writeCharacters("Jean Arp");
writer.writeEndElement();
writer.flush();</pre><p>This code generates the following XML (new lines are non-normative):</p><pre>&lt;?xml version=&rsquo;1.0&rsquo; encoding=&rsquo;utf-8&rsquo;?>
&lt;a b="blah" xmlns:c="http://c" xmlns="http://c">
&lt;d:d d:chris="fry" xmlns:d="http://c"/>Jean Arp&lt;/a></pre>

<a name="bnbfg"></a><h5>Using <tt>XMLEventWriter</tt></h5>
<a name="indexterm-1866"></a><a name="indexterm-1867"></a><p>The <tt>XMLEventWriter</tt> interface in the StAX event iterator API lets applications write back
to an XML stream or create entirely new streams. This API can be
extended, but the main API is as follows:</p><pre>public interface XMLEventWriter {
    public void flush() throws XMLStreamException;
    public void close() throws XMLStreamException;
    public void add(XMLEvent e) throws XMLStreamException;
    // ... other methods not shown.
}</pre><p>Instances of <tt>XMLEventWriter</tt> are created by an instance of <tt>XMLOutputFactory</tt>. Stream events are
added iteratively, and an event cannot be modified after it has been added
to an event writer instance.</p>

<a name="bnbfh"></a><h5>Attributes, Escaping Characters, Binding Prefixes</h5>
<p>StAX implementations are required to buffer the last <tt>StartElement</tt> until an event other
than <tt>Attribute</tt> or <tt>Namespace</tt> is added or encountered in the stream. This means
that when you add an <tt>Attribute</tt> or a <tt>Namespace</tt> to a stream,
it is appended the current <tt>StartElement</tt> event.</p><p>You can use the <tt>Characters</tt> method to escape characters like <tt>&amp;</tt>, <tt>&lt;</tt>, <tt>></tt>, and
<tt>"</tt>.</p><p>The <tt>setPrefix(...)</tt> method can be used to explicitly bind a prefix for use
during output, and the <tt>getPrefix(...)</tt> method can be used to get the current
prefix. Note that by default, <tt>XMLEventWriter</tt> adds namespace bindings to its internal
namespace map. Prefixes go out of scope after the corresponding <tt>EndElement</tt> for the event
in which they are bound.</p>
         </div>
         <div class="navigation">
             <a href="bnbec.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
             <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
             <a href="bnbfi.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
         </div>

         <div class="copyright">
      	    <p>The material in The Java&trade; EE 5 Tutorial is <a href='docinfo.html'>copyright</a>-protected and may not be published in other works without express written permission from Sun Microsystems.</p>
      	 </div>

      </td>
   </tr>
</tbody>
</table>
</body>
</html>

